﻿using CrawlerApp.Core.Entities;
using CrawlerApp.Core.Interfaces;
using CrawlerApp.Infrastructure.Interfaces;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CrawlerApp.Core.Services
{
    public class AccountService : IAccountService
    {
        private readonly IRepository<Account> repository;

        public AccountService(IRepository<Account> repository)
        {
            this.repository = repository;
        }

        public async Task<Account> CreateAccountAsync(string username, CancellationToken cancellationToken = default)
        {
            var account = new Account(username);
            return await repository.AddAsync(account, cancellationToken);
        }

        public async Task<Account> CreateAccountAsync(string username, string password, CancellationToken cancellationToken = default)
        {
            var account = new Account(username).CreateHashPassword(password);
            return await repository.AddAsync(account, cancellationToken);
        }

        public async Task DeleteAccountAsync(Account account, CancellationToken cancellationToken = default)
        {
            await repository.DeleteAsync(account, cancellationToken);
        }

        public async Task DeleteAccountByIdAsync(int id, CancellationToken cancellationToken = default)
        {
            var user = await GetAccountByIdAsync(id, cancellationToken: cancellationToken);
            if(user != null)
            {
                await repository.DeleteAsync(user, cancellationToken);
            }
        }

        public async Task<Account> GetAccountByIdAsync(int id, CancellationToken cancellationToken = default)
        {
            return await repository.GetByIdAsync(id, cancellationToken: cancellationToken);
        }

        public async Task<Account> GetAccountByUserNameAsync(string username, CancellationToken cancellationToken = default)
        {
            return await repository.SingleOrDefaultAsync(it => it.UserName == username, cancellationToken: cancellationToken);
        }

        public async Task<Account> LoginAsync(string username, string password, CancellationToken cancellationToken = default)
        {
            var account = new Account(username).CreateHashPassword(password);
            return await repository.SingleOrDefaultAsync(it => it.UserName == account.UserName && password == account.Password, cancellationToken: cancellationToken);
        }

        public Account CreatePassword(Account account, string password)
        {
            return account.CreateHashPassword(password);
        }

        public Task<Account> SetRoleAsync(Account account, string role, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }
    }
}
